package com.shiroha.notification.handler;

import com.fasterxml.jackson.core.type.TypeReference;
import com.shiroha.common.event.ServiceEvent;
import com.shiroha.common.utils.JsonUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 发送通知的WS处理器
 */
@Component
@Slf4j
public class NotificationWebSocketHandler extends AbstractWebSocketHandler {

    private final Map<UUID, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @EventListener(ServiceEvent.class)
    public void onEvent(ServiceEvent event) {
        try {
            Map<String, Object> payload = event.getDataAsType(new TypeReference<>() {});
            UUID userId = UUID.fromString((String) payload.get("userId"));
            WebSocketSession session = userSessions.get(userId);
            if (session != null && session.isOpen()) {
                session.sendMessage(new TextMessage(JsonUtils.serialize(payload)));
            }
        }catch (Exception e) {
            log.error("反序列化负载失败", e);
        }
    }

    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) throws Exception {
        UUID userId = UUID.fromString(session.getAttributes().get("userId").toString());
        userSessions.put(userId, session);
    }
}
